<?php

namespace App\Models;

use Session;
use Cookie;

class Doctor extends BaseModel
{
    protected $table = "doctor";


    public function __construct( )
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function depart()
    {
        return $this->belongsTo('App\Models\Depart', 'depart_id', 'id');
    }

    /**
     * 根据当前日期生成一个月的序列日期
     */
    public function getdaylist(){
        $daylist = [];
        for($i=0;$i<15;$i++) {
            $date = date("Y-m-d", strtotime("+" . $i . " day"));
            $daylist[] = $date;
        }
        return $daylist;
    }

    /**
     * 获取时间段
     */
    public function getworkTime($request){

          $type = $request['type'];
          $data = getTimeArea($type);
          $rows = [];
          foreach($data as $v){
               $rows[] = $v;
          }
          return $rows;
    }

    public function changeWorkSate($request){
        $where['id'] = $request['id'];
        $updata['status'] = $request['status'];
        $res = $this->up($where,$updata);
        if(!$res){
            return ['state'=>0,'msg'=>'修改失败'];
        }
        return ['state'=>1,'msg'=>'修改成功'];
    }

    public function getWorkTimeIndex($request)
    {
        $where = [];
        $order['id'] = "desc";
        $d_where = [];
        if(!empty($request['keywords'])){
               $d_where['name'] = $request['keywords'];
        }
        $rows = $this->getList($d_where,'*',$order,10);
        if($rows){
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        $work = new Worktime();
        foreach($rows['data'] as $key => $v){
            $where['doctor_id'] = $v['id'];
            $order['add_time'] = "desc";
            $work_data = $work->getList($where,'*',$order);
            if($work_data){
                $work_data = $work_data->toArray();
            }
            if(count($work_data)!=0) {
                $rows['data'][$key]['apointment_type'] = $work_data[0]['apointment_type'];
                $rows['data'][$key]['work_type'] = $work_data[0]['work_type'];
                $rows['data'][$key]['add_time'] = $work_data[0]['add_time'];
            }

        }
        return $rows;
    }
    /**
     * 根据id 获取 医师信息
     */
    public function getDoctorById($request){
        $where['id'] = $request['id'];
        $data = $this->with('depart')->multiWhere($where)->first();
        if(!$data){
            return ['state'=>0,'msg'=>'医师信息错误'];
        }
        $data['pro_tag_arr'] = explode(',',$data['pro_tag']);
        return ['state'=>1,'msg'=>'ok','data'=>$data];
    }
    /**
     * 根据id 获取 医师信息
     */
    public function getDoctorByInfo($request){
          $where['id'] = $request['id'];
          $data = $this->with('depart')->multiWhere($where)->first();
          if(!$data){
              return ['state'=>0,'msg'=>'医师信息错误'];
          }
          $user = new User();
          $uid = isset($request['mid']) ? $request['mid'] : $_GET['mid'];
          $user_info = $user->getUserById(array('id'=>$uid));
          $data = $data->toArray();
          $data['user']['is_vip'] = 0;
          if($user_info['data']['group_id']!=1){
              $data['user']['is_vip'] = 1;
          }
          $reg_type_vip = $data['reg_type_vip'];
          $reg_type = $data['reg_type'];
          $follow = new Follow();
          // 判斷是否已經關注
          $f_where['user_id'] = $uid;
          $f_where['doctor_ids'] = array('like','%"'.$request['id'].'"%');
          $res = $follow->getOne($f_where);
          $his_res_vip = apiCurl('regTypeFee',array('reg_type'=>$reg_type_vip));
          $his_res = apiCurl('regTypeFee',array('reg_type'=>$reg_type));
          $data['res_vip_free'] = $his_res_vip['Fee'] ? $his_res_vip['Fee']:1;
          $data['res_free'] = $his_res['Fee'] ? $his_res['Fee']:1;
          $data['f_state'] = 0;
          if($res){
                $data['f_state'] = 1;
          }
          $data['pro_tag_arr'] = explode(',',$data['pro_tag']);
          return ['state'=>1,'msg'=>'ok','data'=>$data];
    }



    /**
     * @return array获取所有医师
     */
    public function lstDateDoctor($request){
        if($request['key']) {
            $where['add_time'] = date('Y-m-d',strtotime("+".$request['key']." day"));
        }else{
            $where['add_time'] = date('Y-m-d',strtotime("+1". "day"));
        }
        if($request['section_id']){
              $section_id = $request['section_id'];
              $d_where['depart_id'] = $section_id;
        }

        $work = new Worktime();
        $appoint = new Appointment();
        $res = $work->getList($where);
        if($res){
            $res = $res->toArray();
        }
        $res_id =[];
        foreach($res as $v){
            $res_id[]= $v['doctor_id'];
        }
        $d_where['id'] = ['in',$res_id];
        $d_where['status'] = 1;
        $order['sort'] = 'ASC';
        $rows = $this->getList($d_where,'*',$order,10);
        if($rows){
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
       foreach ($rows['data'] as $key => $val) {
            // 判断该医生当前的坐诊计划是否被预约
            $woketimelist = $work->getOne(['doctor_id' => $val['id'], 'add_time' => $where['add_time']]);
            if (!$woketimelist) {
                unset($rows['data'][$key]);
                continue;
            }
            $woketimelist = $woketimelist->toArray();
            $timeArr = json_decode($woketimelist['time_area']);
            if (!$timeArr) {
                unset($rows['data'][$key]);
                continue;
            }
            $num = count($timeArr);
            $condition['mark_time'] = ['between', [strtotime($where['add_time'] . ' ' . $timeArr[0]), strtotime($where['add_time'] . ' ' . $timeArr[$num - 1])]];
            $condition['status'] = 1;
            $res = $appoint->getCount($condition);
            $full = 0;
            if ($num <= $res) {
                $full = 1;
            }
            $rows['data'][$key]['full'] = $full;
            $rows['data'][$key]['pro_tag_arr'] = explode(',', $val['pro_tag']);
        }
        return ['state' => 1, 'msg' => 'ok', 'data' => $rows];
    }

    public function getDoctorList($request)
    {
        $keyword = trim($request['keyword']) ? trim($request['keyword']) : '';
        $where['status'] = ['<',2];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = intval($keyword);
            } else {
                $where['name'] = ['like','%'.$keyword.'%'];
            }
        }
        if ($request['did']) {
            $where['depart_id'] = $request['did'];
        }
        $order['is_hot'] = 'desc';
        $order['id'] = 'asc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'],request('page',1),10);
        }
        return $rows;
    }


    /**
     * 保存编辑
     * @param $request
     * @return array
     */
    public function editDoctor($request){
        $data['name'] = trim($request['name']);
        $data['job'] = trim($request['job']);
        $data['pro_title'] = trim($request['pro_title']);
        $data['pro_tag'] = trim($request['pro_tag']);
        $data['depart_desc'] = trim($request['depart_desc']);
        $data['self_sign'] = trim($request['self_sign']);
        $data['work_exp'] = trim($request['work_exp']);
        $data['depart_id'] = trim($request['depart_id']);
        $data['origin_company'] = trim($request['origin_company']);
        $data['tech_desc'] = trim($request['tech_desc']);
        $data['intro'] = trim($request['intro']);
        $data['reffer_id'] = trim($request['reffer_id']);
        $data['reg_type'] = trim($request['reg_type']);
        $data['reg_type_vip'] = trim($request['reg_type_vip']);
        $data['advice_price'] = trim($request['advice_price']);
        $data['advice_time'] = trim($request['advice_time']);
        $data['customer_service'] = trim($request['customer_service']);
        $data['customer_price'] = trim($request['customer_price']);
        $check = $this->checkParams($data,$request['id']);
        if ($check != 'ok') {
            return $check;
        }
        if ($request['avatar']) {
            $data['avatar'] = upImgs($request['avatar'], 'avatar');
        }

        $where['id'] = $request['id'];
        //dd($where);
        $did = $this->up($where,$data);
        if(!$did){
            $res ="医师编辑失败";
            return $res;
        }
        $res = "医师编辑成功";
        return $res;
    }

    /**
     * 处理排序请求
     */
    public function dealSort($request){
          $sort_key = trim($request['data'],',');
          $arr = explode(',',$sort_key);
          $count = 0;
          foreach($arr as $v){
                $_temarr = explode('=>',$v);
                $updata['sort'] = $_temarr[1];
                $where['id'] = $_temarr[0];
                $res = $this->up($where,$updata);
                if($res){
                    $count++;
                }
          }
          if($count==count($arr)){
                return ['state'=>1,'msg'=>'处理成功'];
          }else{
                return ['state'=>0,'msg'=>'处理失败'];
          }
    }


    /**
     * @param $request
     * @return array
     * 添加医师
     *
     */
    public function addDcotor($request){
        $data['name'] = trim($request['name']);
        $data['job'] = trim($request['job']);
        $data['pro_title'] = trim($request['pro_title']);
        $data['pro_tag'] = trim($request['pro_tag']);
        $data['section_desc'] = trim($request['section_desc']);
        $data['self_sign'] = trim($request['self_sign']);
        $data['work_exp'] = trim($request['work_exp']);
        $data['depart_id'] = trim($request['depart_id']);
        $data['origin_company'] = trim($request['origin_company']);
        $data['tech_desc'] = trim($request['tech_desc']);
        $data['intro'] = trim($request['intro']);
        $data['reffer_id'] = trim($request['reffer_id']);
        $data['reg_type'] = trim($request['reg_type']);
        $data['reg_type_vip'] = trim($request['reg_type_vip']);
        $data['advice_price'] = trim($request['advice_price']);
        $data['advice_time'] = trim($request['advice_time']);
        $data['customer_service'] = trim($request['customer_service']);
        $data['customer_price'] = trim($request['customer_price']);
        $data['created_at'] = date("Y-m-d H:i:s", time());
        $check = $this->checkParams($data);
        if ($check != 'ok') {
            return $check;
        }
        if ($request['avatar']) {
            $data['avatar'] = upImgs($request['avatar'], 'avatar');
        }
        $did = $this->add($data);
        if (!$did) {
            return '医师添加失败';
        }
        return "医师添加成功";
    }
    /**
     * 删除医师
     * @param $request
     * @return array
     */
    public function delDoctor($request){

        $where['id'] = $request['id'];

        $res = $this->up($where,['status'=>2]);
        if (!$res) {
            return ['state' => 0, 'msg'=>'医师删除失败'];
        }
        return ['state' => 1,  'msg'=>'医师删除成功'];

    }

    /**
     * 删除医师
     * @param $request
     * @return array
     */
    public function modifyDoctor($request)
    {

        $where['id'] = $request['id'];
        $res = $this->up($where,['status'=>$request['status']]);
        if (!$res) {
            return ['state' => 0,  'msg'=>'操作失败'];
        }
        return ['state' => 1,  'msg'=>'操作成功'];
    }

    public function changeHot($request)
    {

        $where['id'] = $request['id'];
        $res = $this->up($where,['is_hot'=>$request['status']]);
        if (!$res) {
            return ['state' => 0,  'msg'=>'操作失败'];
        }
        return ['state' => 1,  'msg'=>'操作成功'];
    }



    /**
     * @return array获取所有医师
     */
    public function lstDoctor(){
        $where = [];
        $order['id'] = 'desc';
        $rows = $this->getList($where,'*',$order,5);
        if($rows){
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 5);
        }
        return ['state'=>1,'msg'=>'ok','data'=>$rows];
    }

    public  function regDoctors($sectionId)
    {
        $res = $this->getOne(['id'=>$sectionId]);
//        return $res['']
    }



    public function his_reg_type()
    {
        return ['currtime' => date('Y-m-d H:i:s', time())];
    }

    public function checkParams($params, $id = 0)
    {
        if (!$params['name']) return '请填写医生名称';
        if (!$params['job']) return '请填写职务';
        if (!$params['pro_title']) return '请填写职称';
        if (!$params['depart_desc']) return '请填写所属科室描述';
        if (!$params['self_sign']) return '请填写个性签名';
        if (!$params['work_exp']) return '请填写从业经验';
        if (!$params['origin_company']) return '请填写原所在单位';
        if (!$params['tech_desc']) return '请填写技术专长';
        if (!$params['intro']) return '请填写名医简介';
        if (!$params['depart_id']) return '请选择科室';
        if (!$params['reffer_id']) return '请选择平台医生和his医生关联';
        if (!$params['reg_type']) return '请选择平台医生挂号类别';
        if (!$params['reg_type_vip']) return '请选平台医生挂号类别VIP';
        if ($id) {
            $where['id'] = ['<>', $id];
            $where['name'] = $params['name'];
            $where['depart_id'] = $params['depart_id'];
        } else {
            $where['name'] = $params['name'];
            $where['depart_id'] = $params['depart_id'];
        }
        $res = $this->getOne($where);
        if ($res) {
            return '该科室已有同名同姓'.$params['name'].'医生，请重新输入不同的医生姓名';
        }
        return 'ok';
    }

    public function search($request){
        $where = [];
         if($request['keywords']){
               $where['name'] = array('like','%'.$request['keywords']."%");
         }
         $where['status'] = 1;
        $order['id'] = 'desc';
        $rows = $this->getList($where,'*',$order,10);
        if($rows){
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        foreach($rows['data'] as $key => $val){
            $rows['data'][$key]['pro_tag_arr'] = explode(',',$val['pro_tag']);
        }
        return ['state'=>1,'msg'=>'ok','data'=>$rows];
    }

    /**
     * 获取挂号费用
     * @param $id 传医师id
     */
    public function his_reg_type_fee($param){
        $data['bcb01'] = $param['reg_type'];
        return $data;
    }

    public function his_ask_url($param){
           $data['kfid'] = $param['kfid'];
           $data['uid'] = $param['uid'];
           return $data;
    }

    /**
     * 获取挂号费用
     * @param $id 传医师id
     */
    public function his_reg_fee($param){
          $res = $this->getDoctorById(array('id'=>$param['id']));
          if($param['type']!=1) {
              $data['bcb01'] = $res['data']['reg_type_vip'];
          }else{
              $data['bcb01'] = $res['data']['reg_type'];
          }
          return $data;
    }

}